#ifndef TLS_SAMPLER_H
#define TLS_SAMPLER_H

#include "vector.h"
#include "utils.h"
#include <cmath>

namespace tls{
  struct sampler{
    int n;
    sampler(int num):n(num){}
    virtual ~sampler()=0;
    //[-0.5,+0.5]^2
    virtual vec3 sample()const=0;
    virtual void map_hemisphere(const real&)=0;
  };

  struct jitter:public sampler{
    mutable int iter;
    mutable int base;
    vec3* s;

    jitter(int num):sampler(num){
      base=iter=0;
      s=new vec3[num];
      for(int i=0;i<n;++i){
	s[i].x=rand_real();
	s[i].y=rand_real();
      }

      int w=sqrt(n);
      real u=1.0 / w;
      for(int y=0;y<w;++y){
	for(int x=0;x<w;++x){
	  int i=y*w+x;
	  s[i]=vec3(u,0,0)*x + vec3(0,u,0)*y 
	    +vec3(s[i].x * u,s[i].y * u,0)
	    -vec3(0.5,0.5);
	}
      }
    }

    ~jitter();

    void map_hemisphere(const real& e){
      for(int i=0;i<n;++i){
	real r0=s[i].x + 0.5;
	real r1=s[i].y + 0.5;
	s[i].x=2*pi * r0;
	s[i].y=std::acos(std::pow(1-r1,1/(1+e)));
      }
    }
    vec3 sample()const;
  };

}//namespace tls

#endif
